package com.atguigu.auth.controller;


import com.alibaba.fastjson.TypeReference;
import com.atguigu.auth.feign.MemberFeignService;
import com.atguigu.auth.feign.ThirdPartFeignService;
import com.atguigu.auth.vo.UserLoginVo;
import com.atguigu.auth.vo.UserRegisterVo;
import com.atguigu.common.constants.SessionAttrKeyConstant;
import com.atguigu.common.constants.SmsConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.atguigu.common.constants.SessionAttrKeyConstant.LOGIN_USER;

@Slf4j
@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam(value = "phone") String phone) {

        //TODO 1、接口防刷


        /**防止一个手机号码60s内多次获取短信验证码
         * 解决思路：将短信验证码存储在redis中，key为phoneNum，value为验证码和存储时系统的当前时间。
         * 从redis中查询为null则调用发送短信验证码，若查询不为空则判断是否超过60s，
         * 是则再次调用发送短信验证码，否则返回提示信息。
         */

        String redisCode = stringRedisTemplate.opsForValue().get(SmsConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotEmpty(redisCode)) {
            Long currentTime = Long.parseLong(redisCode.split("_")[1]);
            //活动存入redis的时间，用当前时间减去存入redis的时间，判断用户手机号是否在60s内发送验证码
            if (System.currentTimeMillis() - currentTime < 60000) {
                //60s不能重发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMessage());
            }
        }

        //由于我购买的第三方短信服务不支持字母+数字组合，支持纯数字，所以重新生成验证码
        // String code = UUID.randomUUID().toString().substring(0, 6);
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String codeNum = String.valueOf(code);
        String redisStorage = codeNum + "_" + System.currentTimeMillis();
        //存入redis，防止同一个手机号在60秒内再次发送验证码
        stringRedisTemplate.opsForValue().set(SmsConstant.SMS_CODE_CACHE_PREFIX + phone,
                redisStorage, 10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, codeNum);
        log.info("要发送的验证码为:{}", codeNum);
        return R.ok();
    }


    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vos, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        // BindingResult用于获取校验出错封装的信息
        //校验出错，跳转到注册页
        if (bindingResult.hasErrors()) {

            //把错误信息发给前端展示
            /*bindingResult.getFieldErrors().stream().collect(Collectors.toMap((item)->{
                return item.getField();
            } ,(item)->{
                return item.getDefaultMessage();
            }));*/
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors
                    .toMap(FieldError::getField,
                            FieldError::getDefaultMessage));
            //model无法存放direct的数据，这里要用到RedirectAttributes存放direct后的数据
            redirectAttributes.addFlashAttribute("errors", errors);
            //org.springframework.web.HttpRequestMethodNotSupportedException:
            // Request method 'POST' not supported
            //出现问题的原因：表单的提交使用的是post请求，会原封不动的转发给reg.html，
            // 但是/reg.html（路径映射默认都是get方式访问）
            // return "forward:reg.html";

            //注意:刷新页面时,会重复提交表单数据，因此表单提交的请求最好是重定向，而不是请求转发(url不变)
            //return "reg";

            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //验证码校验
        String code = vos.getCode();
        String s = stringRedisTemplate.opsForValue().get(SmsConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());

        if (StringUtils.isNotEmpty(s)) {
            //验证码校验成功
            if (code.equals(s.split("_")[0])) {//存储加入了系统时间戳，因此，需要分割
                //删除验证码，令牌机制。 【校验过的验证码要立即删掉，防止老的验证码生效】
                stringRedisTemplate.delete(SmsConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());

                //远程服务调用，将数据存储数据库，进行真正的注册
                R r = memberFeignService.regist(vos);
                if (r.getCode() == 0) {
                    //成功     注册成功重定向到登录页
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    //失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            } else {
                //验证码校验失败
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }

        } else {

            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";

        }


    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){

        R login = memberFeignService.login(vo);
        if (login.getCode()==0) {
            //登录成功， 将用户信息存到session
            MemberResponseVo responseVo = login.getData("data", new TypeReference<MemberResponseVo>() {
            });
            session.setAttribute(SessionAttrKeyConstant.LOGIN_USER, responseVo);
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }


    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        //从session先取出来用户的信息，判断用户是否已经登录过了
        Object attribute = session.getAttribute(LOGIN_USER);
        if (attribute==null) {
            return "login";
        }else {
            //如果用户没登录那就跳转到登录页面
            return "redirect:http://gulimall.com";
        }

    }


}
